package com.anhtuan.reminder.tasks;

import java.util.ArrayList;

import com.anhtuan.reminder.providers.TaskItem;
import com.anhtuan.reminder.providers.TasksProviderWrapper;
import com.anhtuan.reminder.ultils.ActionItem;
import com.anhtuan.reminder.ultils.RepeatItem;

import com.anhtuan.reminder.IncomingActivity;
import com.anhtuan.reminder.NotificationDetailActivity;
import com.anhtuan.reminder.R;

import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.support.v4.app.NotificationCompat;
import android.telephony.SmsManager;

public class DoActionTask extends AsyncTask<Void, Void, Void> {

	private final NotificationManager notificationManager;
	private final Context context;
	private final int taskId;
	private TaskItem taskItem = null;

	public DoActionTask(Context context, int taskId) {
		this.context = context;
		this.notificationManager = (NotificationManager) context
				.getSystemService(Context.NOTIFICATION_SERVICE);
		this.taskId = taskId;
	}

	@Override
	protected Void doInBackground(Void... params) {
		taskItem = TasksProviderWrapper.getTaskById(
				context.getContentResolver(), taskId);

		publishProgress();

		return null;
	}

	@Override
	protected void onProgressUpdate(Void... values) {

		if (taskItem != null) {

			Uri sound;
			NotificationCompat.Builder builder;
			PendingIntent notificationDetailPI;
			
			if (taskItem.isActive()) {

				switch (taskItem.getAction()) {

				case ActionItem.ALERT:

					// Set up notification builder
					builder = new NotificationCompat.Builder(
							context)
							.setSmallIcon(R.drawable.action_alert)
							.setContentTitle(
									context.getResources().getString(
											R.string.alert_text))
							.setContentText(taskItem.getSecContent());

					sound = RingtoneManager
							.getDefaultUri(RingtoneManager.TYPE_ALARM);

					// Set notification sound
					if (sound.equals(null)) {
						// Use the first backup
						sound = RingtoneManager
								.getDefaultUri(RingtoneManager.TYPE_RINGTONE);

						if (sound.equals(null)) {
							// Use the second backup
							sound = RingtoneManager
									.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
						}
					}

					builder.setSound(sound)
					.setVibrate(new long[] {1000, 2000, 2000, 1000})
					.setOnlyAlertOnce(false);
					
					// Set up pending intent to launch when user select the
					// notification					
					notificationDetailPI = PendingIntent.getActivity(
							context, 
							taskId, 
							new Intent(context, NotificationDetailActivity.class)
								.setData(NotificationDetailActivity.ALERT_MSG)
								.putExtra(NotificationDetailActivity.ALERT_MSG_KEY, taskItem.getSecContent()),
							PendingIntent.FLAG_UPDATE_CURRENT);

					builder.setContentIntent(notificationDetailPI)
					.setAutoCancel(true);
					
					// Notify the action
					notificationManager.notify(taskId, builder.build());

					break;

				case ActionItem.SEND_SMS:
					
					// Intent filter
					String SENT = context.getResources().getString(R.string.sms_sent_intent_filter);
					String DELIVERED = context.getResources().getString(R.string.sms_delivered_intent_filter);
					
					
					// Set up pending intent when SMS sent or delivered
					PendingIntent sentPI = PendingIntent.getBroadcast(context,
							0,
							new Intent(SENT), 
							PendingIntent.FLAG_UPDATE_CURRENT);
					
					PendingIntent deliveredPI = PendingIntent.getBroadcast(context, 
							0, 
							new Intent(DELIVERED), 
							PendingIntent.FLAG_UPDATE_CURRENT);
					
					// Get SMS Manager
					SmsManager smsManager = SmsManager.getDefault();
					
					int length = taskItem.getThirdContent().length();
					
					if (length > 160) {
						ArrayList<String> massageList = smsManager.divideMessage(taskItem.getThirdContent());
						smsManager.sendMultipartTextMessage(taskItem.getSecContent(), null, massageList, null, null);
					} else {
						smsManager.sendTextMessage(taskItem.getSecContent(), null, taskItem.getThirdContent(), sentPI, deliveredPI);
					}
					
					// Set notification compat builder
					builder = new NotificationCompat.Builder(
							context)
							.setSmallIcon(R.drawable.action_send_sms)
							.setContentTitle(String.format(context.getResources().getString(R.string.sendsms_text), taskItem.getSecContent()))
							.setContentText(taskItem.getThirdContent());
					
					sound = RingtoneManager
							.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

					// Set notification sound
					if (sound == null) {
						// Use the first backup
						sound = RingtoneManager
								.getDefaultUri(RingtoneManager.TYPE_ALARM);

						if (sound == null) {
							// Use the second backup
							sound = RingtoneManager
									.getDefaultUri(RingtoneManager.TYPE_RINGTONE);
						}
					}
					
					builder.setSound(sound)
					.setOnlyAlertOnce(true)
					.setAutoCancel(true);
					
					// Set pending intent to launch activity when user select the notification
					notificationDetailPI = PendingIntent.getActivity(
											context,
											taskId, 
											new Intent(context, NotificationDetailActivity.class)
												.setData(NotificationDetailActivity.SMS_BODY)
												.putExtra(NotificationDetailActivity.SMS_BODY_KEY, 
											taskItem.getThirdContent()),
											PendingIntent.FLAG_UPDATE_CURRENT);
					
					builder.setContentIntent(notificationDetailPI);
					
					notificationManager.notify(taskId, builder.build());
					
					break;

				case ActionItem.OUTGOING_CALL:
									
					Intent outgoingCallIntent = new Intent()
					.setAction(Intent.ACTION_CALL)
					.setData(Uri.parse("tel:" + taskItem.getSecContent()))
					.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
					
					context.startActivity(outgoingCallIntent);
					
					break;

				case ActionItem.INCOMING_CALL:
					
					Intent intent = new Intent();
					intent.setClass(context, IncomingActivity.class);
					intent.putExtra(IncomingActivity.CALLER_NUMBER_TEXT, taskItem.getSecContent());
					intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
					
					context.startActivity(intent);
					
					break;
				default:
					break;
				}
			}
			
			if (taskItem.getRepeat() == RepeatItem.NOT_REPEATED) {
				TasksProviderWrapper.setActive(context.getContentResolver(),
						taskItem.getId(), false);
			}
		}
	}
}
